﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace OneOfAll.Common.Util
{
    public static class XmlHelper
    {
        public static T ToDeserialize<T>(this string xml)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer xmldes = new XmlSerializer(typeof(T));
                    return (T)Convert.ChangeType(xmldes.Deserialize(sr), typeof(T));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("{0}  {1}", ex.StackTrace, ex.Message));
                return default(T);
            }
        }

        /// <summary>
        /// XML序列化保存
        /// </summary>
        /// <param name="obj">保存的对象</param>
        /// <param name="filename">保存的文件路径</param>
        public static void SaveXml(object obj, string filename)
        {
            FileStream fs = null;
            TextWriter writer = null;
            try
            {
                XmlSerializer ser = new XmlSerializer(obj.GetType());
                writer = new StreamWriter(filename);
                ser.Serialize(writer, obj);
            }
            catch(Exception ex)
            {
                Console.WriteLine(("{0}    {1}"), ex.StackTrace, ex.Message);
            }
            finally
            {
                if (fs != null) fs.Close();
                writer.Close();
            }
        }

        /// <summary>
        /// XML序列化读取
        /// </summary>
        /// <param name="obj">保存的对象</param>
        /// <param name="filename">保存的文件路径</param>
        public static object ReadXml(Type type, string filename)
        {
            object data = null;
            FileStream fs = null;
            if (!File.Exists(filename)) return null;
            try
            {
                fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (fs != null)
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    data = serializer.Deserialize(fs);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(("{0}    {1}"), ex.StackTrace, ex.Message);
            }
            finally
            {
                if (fs != null) fs.Close();
            }
            return data;
        }

    }
}
